package com.j2eefast.bussiness.contract.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.j2eefast.bussiness.contract.entity.BusClassifyEntity;
import com.j2eefast.bussiness.contract.entity.BusStandardEntity;
import com.j2eefast.bussiness.contract.entity.PaySetEntity;
import com.j2eefast.bussiness.contract.mapper.BusEquipmentMapper;
import com.j2eefast.bussiness.contract.mapper.BusStandardMapper;
import com.j2eefast.bussiness.contract.mapper.PaySetMapper;
import com.j2eefast.common.core.base.entity.Ztree;
import com.j2eefast.common.core.exception.RxcException;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.MapUtil;
import com.j2eefast.common.core.utils.PageUtil;
import com.j2eefast.common.core.utils.SpringUtil;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.annotation.DataFilter;
import com.j2eefast.framework.utils.Constant;
import com.j2eefast.framework.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * <p>设备规范分类</p>
 *
 * @author: summer
 * @date: 2021-05-31 14:41
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */

@Service
public class BusStandardService extends ServiceImpl<BusStandardMapper, BusStandardEntity> {

    @Resource
    protected BusStandardMapper busStandardMapper;

    @Resource
    protected BusEquipmentMapper busEquipmentMapper;

    /**
     * 页面分页查询
     */
    public PageUtil findPage(Map<String, Object> params) {
        QueryWrapper<BusStandardEntity> r = new QueryWrapper<BusStandardEntity>();
        Page<BusStandardEntity> page = this.baseMapper.selectPage(new Query<BusStandardEntity>(params).getPage(), r);
        return new PageUtil(page);
    }

    public boolean updateQuit(BusStandardEntity busStandardEntity){
        return busStandardMapper.updateQuit(busStandardEntity);
       // return true;
    }

//    public boolean repairSave(HttpServletRequest request, Model model) throws ParseException {
//        String total_items = request.getParameter("total_items");//认领插入条数
//        int equipmentId =Integer.parseInt(request.getParameter("equipmentId"));
//        //int ids = Integer.parseInt(request.getParameter("id"));//认领插入条数
//        ValidatorUtil.validateEntity(total_items);
//        int total = Integer.valueOf(total_items);
//        List<BusRepairEntity> recordList = new ArrayList<BusRepairEntity>();//更新数据放这里面
//        List<BusRepairEntity> recordList1 = new ArrayList<BusRepairEntity>();//新增数据放这里
//        BusRepairEntity user = new BusRepairEntity();
//        BusEquipmentEntity busEquipmentEntity = busEquipmentMapper.equipmentInfo(equipmentId);
//
//        for (int i = 1; i <= total; i++) {
//            String id = "id_" + i;
//            String sendTime = "sendTime_" + i;
//            String repairTime = "repairTime_" + i;
//            String repairMoney = "repairMoney_" + i;
//            String repairStatus = "repairStatus_" + i;
//            String faultReason = "faultReason_" + i;
//            String remark = "remark_" + i;
//            Date date = new Date();//创建一个时间对象，获取到当前的时间
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
//            user.setSendTime(simpleDateFormat.parse(request.getParameter(sendTime)));
//            user.setRepairTime(simpleDateFormat.parse(request.getParameter(repairTime)));
//            user.setRepairMoney(request.getParameter(repairMoney));
//            user.setRepairStatus(request.getParameter(repairStatus));
//            user.setFaultReason(request.getParameter(faultReason));
//            user.setRemark(request.getParameter(remark));
//            user.setEquipmentId(equipmentId);
//            user.setEquipmentCode(busEquipmentEntity.getEquipmentCode());
//            user.setEquipmentName(busEquipmentEntity.getEquipmentName());
//            user.setEquipmentModel(busEquipmentEntity.getEquipmentModel());
//            user.setMeteringUnit(busEquipmentEntity.getMeteringUnit());
//            if (request.getParameter(id) != "") {
//                user.setId(Integer.parseInt(request.getParameter(id)));
//                //先去查询是否有记录
//                BusRepairEntity info = this.repairInfo(user.getId());
//                if (info != null) {
//                    recordList.add(user);
//                } else
//                    recordList1.add(user);
//            }else
//                recordList1.add(user);
//        }
//
//        if (recordList != null && !recordList.isEmpty()) {
//            this.updateRepair(recordList);
//        }
//        if (recordList1 != null && !recordList1.isEmpty()) {
//            return this.saveRepair(recordList1) ? true : false;
//        }
//        return true;
//    }

    @Transactional(rollbackFor = Exception.class)
    boolean saveRepair( List<BusStandardEntity> recordList){
        return busStandardMapper.saveRepair(recordList);
    }

    @Transactional(rollbackFor = Exception.class)
   boolean updateRepair( List<BusStandardEntity> recordList){
        return busStandardMapper.updateRepair(recordList);
   }



   public BusStandardEntity repairInfo(int id){
        return busStandardMapper.repairInfo(id);
    }


   public List<BusStandardEntity> repairList(int id){
        return busStandardMapper.repairList(id);
    }

    public boolean deleteByIds(Long[] ids) {

        return busStandardMapper.deleteByIds(ids);

    }

    public boolean updateCheck(Long id) {
        Long userId= UserUtils.getUserInfo().getId();

        return busStandardMapper.updateCheck(id ,userId);

    }




    public List<BusStandardEntity> findList(Map<String, Object> params) {
        return SpringUtil.getAopProxy(this).getDeptList(params);
    }
    @DataFilter(compAlias="c",deptAlias = "c")
    public List<BusStandardEntity> getDeptList(Map<String, Object> params){
        String className = (String)params.get("className");
        String parentId =(String)params.get("parentId");

        return this.baseMapper.getDeptList(
//                StrUtil.nullToDefault(className,""),
//                StrUtil.nullToDefault(parentId,""),
                (String) params.get(Constant.SQL_FILTER));
    }
    public BusStandardEntity findCompById(Long id) {
        return busStandardMapper.findCompById(id);
    }
    /**
     * 查询公司树
     * @return
     */
    public List<Ztree> findCompTree( Long parentId) {
        Map<String,Object> mapp = new HashMap<>();
        mapp.put("parentId",parentId);
        List<BusStandardEntity> list = SpringUtil.getAopProxy(this).getDeptList(mapp);
        List<Ztree> ztrees = initZtree(list);
        return ztrees;
    }
    public List<Ztree> initZtree(List<BusStandardEntity> list) {
        return  initZtree(list,null);
    }
    public List<Ztree> initZtree(List<BusStandardEntity> compList, List<String> roleCompList){

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = !ToolUtil.isEmpty(roleCompList);
        for (BusStandardEntity comp : compList) {
            Ztree ztree = new Ztree();
            ztree.setId(comp.getId());
            ztree.setpId(comp.getParentId());
            ztree.setName(comp.getStandardName());
            ztree.setTitle(comp.getStandardName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public void checkDataScope(Long... ids) {
//        if (!UserUtils.hasAnyRoleKeys(Constant.SU_ADMIN)) {
        //check current user has data scope for the deleted use
        Map<String, Object> params = Maps.newConcurrentMap();
        params.put("ids", ids);
        List<?> listData =SpringUtil.getAopProxy(this).getDeptList(params);
        if (null == listData || listData.size() == 0 || listData.size() != ids.length) {
            throw new RxcException(ToolUtil.message("illegal request"),"50001");
        }
//        }
    }

    public boolean checkCompNameUnique(BusStandardEntity comp) {
        Long compId = ToolUtil.isEmpty(comp.getId()) ? -1L : comp.getId();
        BusStandardEntity info = this.getOne(new QueryWrapper<BusStandardEntity>().
                eq("id",comp.getId()).eq("parent_id",comp.getParentId()));
        if (ToolUtil.isNotEmpty(info) && info.getId().longValue() != compId.longValue())
        {
            return  false;
        }
        return true;
    }

    public boolean add(BusStandardEntity comp){
        Date date = new Date();//创建一个时间对象，获取到当前的时间
        comp.setCreateTime(date);
        String userId= UserUtils.getUserInfo().getName();
        comp.setCreateBy(userId);
        if(this.save(comp)){
            return true;
        }
        return false;
    }
    public boolean update(BusStandardEntity comp){
        if(this.updateById(comp)){
            return true;
        }
        return false;
    }
    /**
     * 通过id删除
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delSysCompById(Long id) {

        // 先判断是否有子公司
        List<BusStandardEntity> list = this.listByMap(new MapUtil().put("parent_id", id));
        if (ToolUtil.isNotEmpty(list)) {
            throw new RxcException("请先删除子分类","50001");
        }
        // 在判断公司是否有分配到用户上面如果改公司已经分配到用户上,先删除用户在删
        List<BusStandardEntity> users = busStandardMapper.listByMap(id);
        if (ToolUtil.isNotEmpty(users)) {
            throw new RxcException("请先删除关联分类","50001");
        }
        //删除关联地区
        //   busClassifyMapper.removeByMap(id);

        if(this.removeById(id)){
            return true;
        }else{
            return false;
        }
    }






}
